package cc.aliza.lib.mongo.core.listener;

import cc.aliza.lib.mongo.core.annotations.Default;
import cc.aliza.lib.mongo.core.annotations.Ref;
import cc.aliza.lib.mongo.core.annotations.RefList;
import cc.aliza.lib.mongo.core.cache.FieldsCache;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public class CascadeChecker {

    public static boolean needListener(Class<?> clazz) {
        Field[] fields = FieldsCache.getInstance().get(clazz);
        return Arrays.stream(fields).anyMatch(o -> {
            Ref ref = o.getAnnotation(Ref.class);
            String cascade = Default.CASCADE;
            if (ref != null) {
                cascade = ref.cascade().toUpperCase();
            } else {
                RefList refList = o.getAnnotation(RefList.class);
                if (refList != null) {
                    cascade = refList.cascade().toUpperCase();
                }
            }
            return cascade.contains(Default.CASCADE_DELETE) || cascade.contains(Default.CASCADE_UPDATE) || cascade.contains(Default.CASCADE_CREATE);
        });
    }
}
